/// ===========================================================================
/// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
/// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
/// PURPOSE.
/// ===========================================================================
/// 
/// Project:        MOSS Faceted Search
/// Author:         Leonid Lyublinski (leonidly@microsoft.com)
/// Company:        Microsoft Services
/// Date:           05/04/2007  Version:        1.0
///
/// ===========================================================================

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Serialization;
using System.Data;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using EntLib = Microsoft.Practices.EnterpriseLibrary;

namespace Microsoft.SharePoint.Portal.ExtendedSearch.WebControls
{
    /// <summary>
    /// SP web part used as a cache container.
    /// The web part bound to the querystring in and out.
    /// </summary>
    [System.Web.AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand, Level = System.Web.AspNetHostingPermissionLevel.Minimal)]
    [System.Web.AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = System.Web.AspNetHostingPermissionLevel.Minimal)]
    [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)]
    [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Execution = true)]
    //[Microsoft.SharePoint.Security.SharePointPermission(System.Security.Permissions.SecurityAction.Demand, ObjectModel = true)]
    //[System.Security.Permissions.RegistryPermission(System.Security.Permissions.SecurityAction.Demand, Unrestricted = true)]
    //[Microsoft.SharePoint.Security.WebPartPermission(System.Security.Permissions.SecurityAction.Demand, Connections = true)]
    //[ToolboxData("<{0}:SearchBreadCrumbs runat=server></{0}:SearchBreadCrumbs>")]
    [XmlRoot(Namespace = "Microsoft.SharePoint.Portal.ExtendedSearch")]
    //public sealed class SearchCache : Microsoft.SharePoint.WebPartPages.WebPart
    public sealed class SearchCache : System.Web.UI.WebControls.WebParts.WebPart, IWebPartParameters
    {
        #region Constants

        #endregion

        #region Fields
        private string _cache;
        private string _cacheKey;
        private DateTime _cacheUpdated;
        #endregion

        #region Properties

        /// <summary>
        /// This is a property to store user scoped cache
        /// </summary>
        [WebBrowsable(false)]
        [Category("Cache Settings")]
        [WebPartStorage(Storage.Personal)]
        [WebDisplayName("Cache")]
        [WebDescription("Cached structure of the search results.")]
        public string Cache
        {
            get { return _cache; }
            set { _cache = value; }
        }
        /// <summary>
        /// This is a property to store user scoped cache
        /// </summary>
        [WebBrowsable(false)]
        [Category("Cache Settings")]
        [WebPartStorage(Storage.Personal)]
        [WebDisplayName("Cache Key")]
        [WebDescription("Unique key that defines the cache.")]
        public string LongCacheKey
        {
            get { return _cacheKey; }
            set { _cacheKey = value; }
        }
        /// <summary>
        /// This is a property to store user scoped cache
        /// </summary>
        [WebBrowsable(false)]
        [Category("Cache Settings")]
        [WebPartStorage(Storage.Personal)]
        [WebDisplayName("Cache Updated")]
        [WebDescription("The time when the cache was updated.")]
        public DateTime CacheUpdated
        {
            get { return _cacheUpdated; }
            set { _cacheUpdated = value; }
        }
        #endregion

        #region CTOR
        public SearchCache()
        {
            this.SetPersonalizationDirty();
        }
        #endregion

        #region Delegates

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            LiteralControl ctrl = new LiteralControl(string.Format("<b>{0}</b>", LongCacheKey));
            ctrl.EnableViewState = false;
            Controls.Add(ctrl);
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Rested the cache
        /// </summary>
        public void InvalidateCache()
        {
            Cache = null;
            LongCacheKey = null;
            CacheUpdated = DateTime.MinValue;
        }

        /// <summary>
        /// Returns cached DataTable
        /// </summary>
        /// <returns></returns>
        public DataTable ReadCache()
        {
            DataTable dt = Common.Cache.ReadFromCache(Cache);
            return dt;
        }

        /// <summary>
        /// Updates the we part properties
        /// </summary>
        /// <param name="key"></param>
        /// <param name="updated"></param>
        /// <param name="dt"></param>
        public void UpdateCache(string key, DateTime updated, DataTable dt)
        {
            //this.SaveProperties = true;

            LongCacheKey = key;
            CacheUpdated = DateTime.Now;
            Cache = Common.Cache.WriteToCache(dt);
            //WebPartManager wpm = this.WebPartManager;


        }
        #endregion

        [ConnectionProvider("Cache Provider", "CacheProvider", AllowsMultipleConnections = false)]
        public IWebPartParameters CacheProvider()
        {
            return this;
        }

        private PropertyDescriptorCollection _objParameters;
        public PropertyDescriptorCollection Parameters
        {
            get { return _objParameters; }
            set { _objParameters = value; }
        }

        #region IWebPartParameters Members

        public void GetParametersData(ParametersCallback callback)
        {
            StateBag objParameters = new StateBag();
            foreach (PropertyDescriptor objProperty in Parameters)
            {
                objParameters.Add(objProperty.Name, Parameters[objProperty.Name]);                
            }
            callback.Invoke(objParameters);
        }

        public PropertyDescriptorCollection Schema
        {
            get
            {

                PropertyDescriptorCollection objProperties;
                PropertyDescriptor[] arrProperties = new PropertyDescriptor[Parameters.Count];

                objProperties = TypeDescriptor.GetProperties(this);
                int intParameterCount = 0;
                foreach (PropertyDescriptor objProperty in Parameters)
                {
                    if (Parameters[objProperty.Name] != null)
                    {
                        intParameterCount++;
                        arrProperties[intParameterCount] = objProperty;
                    }
                }

                objProperties = new PropertyDescriptorCollection(arrProperties);
                return objProperties;
            }
        }

        public void SetConsumerSchema(PropertyDescriptorCollection schema)
        {
            Parameters = schema;
        }

        #endregion
    }
}
